package com.weijian.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.weijian.common.enums.GlobalErrorCodeConstants;
import com.weijian.common.exception.ServiceException;
import com.weijian.common.pojo.CommonResult;
import com.weijian.constants.RedisConstants;
import com.weijian.dal.entity.Category;
import com.weijian.dal.entity.Item;
import com.weijian.mapper.CategoryMapper;
import com.weijian.service.CategoryService;
import com.weijian.service.ItemService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 分类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    final StringRedisTemplate stringRedisTemplate;

    final ItemService itemService;

    @Override
    public CommonResult<List<Category>> queryCategoryByIds(List<Long> ids) {
        return null;
    }

    @Override
    public CommonResult<Category> queryCategoryById(Long id) {
        String categoryKey = RedisConstants.CACHE_CATEGORY_KEY + id;
        String categoryJson = stringRedisTemplate.opsForValue().get(categoryKey);
        log.info("分类：{}", categoryJson);
        if (categoryJson != null) {
            return CommonResult.success(JSONUtil.toBean(categoryJson, Category.class));
        }
        Category category = getById(id);
        if (category == null) {
            return CommonResult.error(GlobalErrorCodeConstants.NOT_FOUND);
        }
        stringRedisTemplate.opsForValue().set(categoryKey, JSONUtil.toJsonStr(category));
        return CommonResult.success(category);
    }

    @Override
    public void updateCategory(Category category) {
        if (category.getId() == null) {
            throw new ServiceException(400, "商品为空");
        }
        log.info("更新分类：{}", category);
        updateById(category);
        stringRedisTemplate.delete(RedisConstants.CACHE_CATEGORY_KEY + category.getId());
    }

    @Override
    public void deleteCategoryById(Long id) {
        boolean remove = removeById(id);
        Long count = itemService.lambdaQuery().eq(Item::getCategoryId, id).count();
        if (count > 0) {
            throw new ServiceException(400, "该分类下有商品，不能删除");
        }
        if (!remove) {
            throw new ServiceException(400, "删除商品失败");
        }
        stringRedisTemplate.delete(RedisConstants.CACHE_CATEGORY_KEY + id);
    }

    @Override
    public void deleteCategoryByIds(List<Long> ids) {
        ids.forEach(id -> {
            Long count = itemService.lambdaQuery().eq(Item::getCategoryId, id).count();
            if (count > 0) {
                throw new ServiceException(400, "该分类下有商品，不能删除");
            }
        });
        CategoryService proxy = (CategoryService) AopContext.currentProxy();
        boolean removed = proxy.removeBatchByIds(ids);
        if (!removed) {
            throw new ServiceException(400, "删除商品失败");
        }
        ids.forEach(id -> stringRedisTemplate.delete(RedisConstants.CACHE_CATEGORY_KEY + id));
    }

    @Override
    public CommonResult<List<Category>> listByTypeId(Long categoryId) {
        List<Category> categories = lambdaQuery()
                .eq(Category::getId, categoryId)
                .list();
        return CommonResult.success(categories);
    }
}
